<template>
  <section class="sign-in">
    <el-form ref="form_signIn" :model="form_signIn" :rules="rules_signIn">
      <el-form-item prop="username">
        <el-input v-model="form_signIn.username" autocomplete="off" placeholder="手机号/邮箱" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          ref="inputPassword"
          v-model="form_signIn.password"
          type="password"
          autocomplete="off"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
    </el-form>
    <div class="wrap-btn">
      <a class="btn-forgetPassword" @click="$emit('showForgetPassword')">
        忘记密码
      </a>
    </div>
    <button class="btn-submit" @click="submitForm('form_signIn')">
      登录
    </button>

    <el-dialog
      width="30%"
      title="安全验证"
      :visible.sync="isShowGifCode"
      :lock-scroll="false"
      append-to-body
    >
      <gif-code v-if="hackReset" @closeGifCode="showGifCode" />
    </el-dialog>
  </section>
</template>

<script>
// 引入工具
import { isEmail, isPhone } from '~/assets/js/util.js'
import GifCode from '~/components/header/GifCode'

export default {
  name: 'SignIn',
  components: {
    GifCode
  },
  props: {
    phoneNumber: {
      type: String,
      default: () => ''
    }
  },
  data() {
    const validateUsername = async (rule, value, callback) => {
      let params = {}
      if (value === '') {
        callback(new Error('请输入手机号/邮箱'))
        return
      } else if (isEmail(value)) {
        params = {
          email: value
        }
      } else if (isPhone(value)) {
        params = {
          phone: value
        }
      } else {
        callback(new Error('请输入正确的手机号/邮箱'))
        return
      }

      // 检测手机号/邮箱是否已注册
      try {
        const res = await this.$axios.$post('/api/code/check', params)
        if (res.status === 501) {
          callback()
        } else {
          callback(new Error(res.msg))
        }
      } catch (err) {
        callback(new Error(err))
      }
    }

    return {
      hackReset: false,
      isShowGifCode: false,
      isGifSignIn: false,
      loading: false,
      form_signIn: {
        username: '',
        password: ''
      },
      rules_signIn: {
        username: [
          {
            validator: validateUsername,
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 8, max: 16, message: '密码为8~16位', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    userData() {
      return this.$store.state.user.userData
    }
  },
  watch: {
    // 还原注册窗口携带的手机号
    phoneNumber: function (newVal) {
      if (isPhone(newVal)) {
        this.form_signIn.username = newVal
      }
    }
  },
  methods: {
    showGifCode(boolean) {
      this.toSignIn()
      this.isShowGifCode = boolean
    },
    async successCallback(userToken) {
      this.loading = true
      // 请求用户数据
      await this.$store.dispatch('updateUserDataAction', userToken)
      // 等待获取到用户信息才算登录成功
      this.loading = false
      // 关闭对话框
      this.$emit('onClose')
      // 重置表单
      this.resetForm('form_signIn')
      // 刷新页面
      window.location.reload()
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    async toSignIn() {
      const params = this.form_signIn
      const res = await this.$axios.$post('/api/user/login', params)
      if (res.status === 200) {
        // 登录成功后做的事
        this.successCallback(res.data)
      } else if ([1005, 1008].includes(res.status)) {
        this.$alert(res.msg, '提示', {
          confirmButtonText: '确定',
          type: 'error',
          lockScroll: false,
          callback: () => {
            this.form_signIn.password = ''
            this.$refs.inputPassword.focus()
            if (res.status === 1008) {
              this.isGifSignIn = true
            }
          }
        })
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isGifSignIn) {
            // 强制刷新组件
            this.hackReset = false
            this.$nextTick(() => {
              this.hackReset = true
            })
            this.isShowGifCode = true
          } else {
            this.toSignIn()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import "~assets/css/public";
.sign-in {
  .wrap-btn {
    display: flex;
    justify-content: flex-end;
    height: 14px;

    a.btn-forgetPassword {
      cursor: pointer;
      color: #999;
      margin-right: 6px;
      margin-top: -16px;
    }
  }
}
</style>
